<template>
  <d2-container>
    <template slot="header">
      <div class="header">
        <h1>课程信息</h1>
        <div>
          <el-form
            :inline="true"
            :model="queryForm"
            class="demo-form-inline query_form"
            ref="queryForm"
          >
            <el-form-item class="query_item" prop="courseName" size="small" label="课程名称">
              <el-input v-model="queryForm.courseName" placeholder="课程名称"></el-input>
            </el-form-item>
            <el-form-item class="query_item" prop="courseProducer" size="small" label="课程提供方">
              <el-input v-model="queryForm.courseProducer" placeholder="课程提供方"></el-input>
            </el-form-item>
            <el-form-item class="query_item" prop="skillId" size="small" label="课程标签">
              <el-select v-model="queryForm.skillId" placeholder="课程标签">
                <el-option label="所有" value=""></el-option>
                <el-option v-for="(skillName, skillId) in skillNames" :label="skillName" :value="skillId" :key="skillId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="query_item" prop="status" size="small" label="上架状态">
              <el-select v-model="queryForm.status" placeholder="上架状态">
                <el-option label="所有" value=""></el-option>
                <el-option label="上架" value="1"></el-option>
                <el-option label="下架" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="query_item" size="small">
              <el-button type="primary" @click="queryCourseBtn()">查询</el-button>
              <el-button @click="resetQueryForm('queryForm')">重置</el-button>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="addCourseBtn()">添加课程</el-button>
        </div>
      </div>
    </template>
    <el-table
      class="table"
      :data="tableData"
      stripe
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column
        type="index"
        width="50"
        align="center"
      >
      </el-table-column>
      <el-table-column
        v-for="(val_en, key_ch) in colLabel"
        :key="val_en"
        :prop="key_ch"
        :label="val_en"
        min-width="150"
        sortable
        show-overflow-tooltip
        header-align="center"
      >
      </el-table-column>
      <el-table-column
        min-width="220"
        header-align="center"
        label="操作"
        fixed="right">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="detailCourseBtn(scope.$index, tableData)"
            type="default"
            size="small">
            详情
          </el-button>
          <el-button
            @click.native.prevent="updateCourseBtn(scope.$index, tableData)"
            type="primary"
            size="small">
            修改
          </el-button>
          <el-button
            @click.native.prevent="deleteCourseBtn(scope.$index, tableData)"
            type="danger"
            size="small">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="showUpdateDialog"
      width="30%"
      :before-close="handleClose"
      class="operate_dialog"
    >
      <div class="operate_course" v-if="showUpdateDialog">
        <el-form
          ref="operateForm"
          :model="operateForm"
          :rules="course_rules"
          :disabled="operateDisabled"
          label-width="auto"
          class="operate_form"
        >
          <div class="main">
            <el-form-item label="课程名称" prop="courseName">
              <el-input v-model="operateForm.courseName"></el-input>
            </el-form-item>
            <div class="upload">
              <el-form-item label="上传图片" prop="courseImagesId">
                <el-upload
                  ref="imageUpload"
                  action="/api/sys/imageUpload/"
                  list-type="picture"
                  :auto-upload="false"
                  :limit="1"
                  :on-change="handleChange"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <span slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10MB</span>
                </el-upload>
              </el-form-item>
            </div>
            <el-form-item label="提供方" prop="courseProducer">
              <el-input v-model="operateForm.courseProducer"></el-input>
            </el-form-item>
                <el-form-item label="课时" prop="lessonNum">
                  <el-input v-model="operateForm.lessonNum"></el-input>
                </el-form-item>
                <el-form-item label="课程时长" prop="courseDuration">
                  <el-input v-model="operateForm.courseDuration"></el-input>
                </el-form-item>
                <el-form-item label="课程原价" prop="courseOriginalPrice">
                  <el-input v-model="operateForm.courseOriginalPrice"></el-input>
                </el-form-item>
                <el-form-item label="课程现价" prop="courseDiscountPrice">
                  <el-input v-model="operateForm.courseDiscountPrice"></el-input>
                </el-form-item>
                <el-form-item label="课程报名分数" prop="satisfiedScore">
                  <el-input v-model="operateForm.satisfiedScore"></el-input>
                </el-form-item>
                <el-form-item label="课程属于职业" prop="profession">
                  <el-input v-model="operateForm.profession"></el-input>
                </el-form-item>
            <div class="switch-div">
              <div class="col">
                <el-form-item label="资源标识" prop="recourseSign">
                  <el-switch
                    v-model="operateForm.recourseSign"
                    active-value="1"
                    inactive-value="0"
                  ></el-switch>
                </el-form-item>
              </div>
              <div class="col">
                <el-form-item label="向公众开放" prop="isOpen">
                  <el-switch
                    v-model="operateForm.isOpen"
                    active-value="1"
                    inactive-value="0"
                  ></el-switch>
                </el-form-item>
              </div>
              <div class="col">
                <el-form-item label="热门" prop="isHot">
                  <el-switch
                    v-model="operateForm.isHot"
                    active-value="1"
                    inactive-value="0"
                  ></el-switch>
                </el-form-item>
              </div>
              <div class="col">
                <el-form-item label="推荐页面" prop="isRecommend">
                  <el-switch
                    v-model="operateForm.isRecommend"
                    active-value="1"
                    inactive-value="0"
                  ></el-switch>
                </el-form-item>
              </div>
              <div class="col">
                <el-form-item label="收费" prop="isSold">
                  <el-switch
                    v-model="operateForm.isSold"
                    active-value="1"
                    inactive-value="0"
                  ></el-switch>
                </el-form-item>
              </div>
            </div>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="operateForm.status" size="small">
                <el-radio-button label="0">上架</el-radio-button>
                <el-radio-button label="1">下架</el-radio-button>
                <el-radio-button label="2">SP审核</el-radio-button>
                <el-radio-button label="3">管理员审核</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="类型" prop="typeId">
              <el-select v-model="operateForm.typeId" placeholder="请选择类型">
                <el-option v-for="(typeName, typeId) in typeNames" :label="typeName" :value="typeId" :key="typeId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="教师" prop="teacherId">
              <el-select v-model="operateForm.teacherId" placeholder="请选择教师">
                <el-option label="教师1" value="1"></el-option>
                <el-option label="教师2" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="标签" prop="skillId">
              <el-select v-model="operateForm.skillId" placeholder="请选择标签">
                <el-option v-for="(skillName, skillId) in skillNames" :label="skillName" :value="skillId" :key="skillId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="课程介绍" prop="courseDetail">
              <el-input type="textarea" v-model="operateForm.courseDetail"></el-input>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button v-if="!operateDisabled" @click="showUpdateDialog = false">取 消</el-button>
    <el-button v-if="!operateDisabled" type="primary" @click="DialogClick(operateForm)">确 定</el-button>
  </span>
    </el-dialog>
    <template slot="footer">
      <div class="pagination">
        <el-pagination
          background
          :current-page="page"
          :page-size="size"
          :pager-count="5"
          layout="prev, pager, next, jumper"
          :total="params.total"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </template>
  </d2-container>
</template>

<script>
import { GetCourse, AddCourse, UpdateCourse, DelCourse } from '@api/course/index'
import { GetAllSkill } from '@api/skill/index'
import { GetAllType } from '@api/type/index'

import uuidv1 from 'uuid/v1'

export default {
  name: 'index',
  data () {
    return {
      tableData: [],
      colName_ch: {
        courseId: '课程ID',
        courseName: '课程名称',
        createTime: '课程创建时间',
        createName: '课程创建人',
        updateTime: '课程修改时间',
        updateName: '课程修改人',
        delSign: '删除标识',
        isOpen: '是否向公众开放',
        status: '上架状态',
        isHot: '是否热门',
        isRecommend: '是否推荐首页',
        lessonNum: '课时',
        courseOriginalPrice: '课程原价',
        courseDiscountPrice: '课程现价',
        applicationsNumber: '报名人数',
        courseDuration: '课程时长',
        courseProducer: '课程提供方',
        courseGrade: '课程等级',
        courseDetail: '课程介绍',
        satisfiedScore: '课程报名分数',
        profession: '课程属于职业',
        recourseSign: '资源标识',
        isOpenName: '是否公开文字描述',
        statusName: '上架状态文字描述',
        courseImagesId: '课程图片ID',
        teacherId: '教师ID',
        skillId: '标签ID',
        typeId: '类别ID',
        isSold: '是否付费'
      },
      showLabel: [
        'courseName',
        'lessonNum',
        'courseDuration',
        'courseOriginalPrice',
        'courseDiscountPrice',
        'applicationsNumber',
        'courseProducer',
        'courseGrade',
        'courseDetail',
        'satisfiedScore',
        'profession',
        'status',
        'delSign'
      ],
      params: {},
      queryForm: {
        courseName: '',
        status: '',
        courseProducer: '',
        skillId: ''
      },
      operateForm: {
        courseId: '',
        courseName: '',
        createTime: '',
        createName: '',
        updateTime: '',
        updateName: '',
        delSign: '',
        isOpen: '',
        status: '',
        isHot: '',
        isRecommend: '',
        lessonNum: '',
        courseOriginalPrice: '',
        courseDiscountPrice: '',
        applicationsNumber: '',
        courseDuration: '',
        courseProducer: '',
        courseGrade: '',
        courseDetail: '',
        satisfiedScore: '',
        profession: '',
        recourseSign: '',
        isOpenName: '',
        statusName: '',
        courseImagesId: '',
        teacherId: '',
        skillId: '',
        typeId: '',
        isSold: ''
      },
      page: 1,
      size: 12,
      showUpdateDialog: false,
      operateString: '',
      dialogTitle: '新增课程',
      course_rules: {
        courseName: [
          {
            required: true,
            message: '课程名称不能为空',
            trigger: 'change'
          },
          {}
        ],
        courseImagesId: [
          {
            required: true,
            message: '课程图片Id不能为空',
            trigger: ''
          },
          {}
        ],
        courseProducer: [
          {
            required: true,
            message: '课程提供方不能为空',
            trigger: 'blur'
          },
          {}
        ],
        lessonNum: [
          {
            required: true,
            message: '课时不能为空',
            trigger: 'blur'
          }
        ],
        courseDuration: [
          {
            required: true,
            message: '课程时长不能为空',
            trigger: 'blur'
          }
        ],
        courseOriginalPrice: [
        ],
        courseDiscountPrice: [
        ],
        satisfiedScore: [
          {
            required: false,
            trigger: 'blur',
            message: '课程报名分数必须为数字值'
          }
        ],
        profession: [
          {
            required: true,
            message: '课程职业不能为空',
            trigger: 'blur'
          }
        ],
        recourseSign: [],
        isOpen: [
          {
            required: true,
            trigger: 'change'
          }
        ],
        isHot: [
          {
            required: true,
            trigger: 'change'
          }
        ],
        isRecommend: [
          {
            required: true,
            trigger: 'change'
          }
        ],
        isSold: [
          {
            required: true,
            trigger: 'change'
          }
        ],
        status: [
          {
            required: true,
            message: '上架状态不能为空',
            trigger: 'blur'
          }
        ],
        typeId: [
          {
            required: true,
            message: '类别Id不能为空',
            trigger: 'blur'
          }
        ],
        teacherId: [
          {
            required: true,
            message: '教师Id不能为空',
            trigger: 'blur'
          }
        ],
        skillId: [
          {
            required: true,
            message: '标签Id不能为空',
            trigger: 'blur'
          }
        ],
        courseDetail: []
      },
      skillData: [],
      typeData: [],
      operateDisabled: false,
      fileList: [],
      dialogImageUrl: '',
      uploadUrl: '',
      token: '',
      uploadHeader: {
      },
      spId: 'user'
    }
  },
  methods: {
    /**
       * @description 调用api get接口，获取课程数据
       * @param {Object} params 查询参数
       * @return {Object} response 查询结果
       */
    async getCourseByApi (params) {
      let response
      await GetCourse(params).then(res => {
        response = res
      })
      return response
    },
    /**
       * @description 调用api add接口，添加一行数据
       * @param {Object} params 查询参数
       */
    async addCourseByApi (params) {
      await AddCourse(params).then(res => {
        console.log(res.data)
      })
    },
    /**
     * @description 调用api update接口，修改一行数据
     * @param {Object} params 修改参数
     */
    async updateCourseByApi (params) {
      await UpdateCourse(params).then(res => {
        console.log(res.data)
      })
    },
    /**
     * @description 调用api delete接口，将delSign设置为1
     * @param {Object} params 修改参数
     */
    delCourseByApi (params) {
      DelCourse(params).then(res => {
        console.log(res.data)
      })
    },
    /**
       * 根据查询参数和用户id获取tableData表格数据和total数据总数
       * @param {Object} params 查询参数
       */
    getCourse (params) {
      // 添加spId
      params['spId'] = this.spId
      this.getCourseByApi(params).then(res => {
        this.tableData = res.data.records
        this.params.total = res.data.total
      })
    },
    addCourse (formName) {
      this.$refs['operateForm'].validate((valid) => {
        console.log(valid)
        if (valid) {
          this.$refs.imageUpload.submit()
          this.params['courseName'] = this.operateForm.courseName
          this.params['courseImagesId'] = this.operateForm.courseImagesId
          this.params['courseOriginalPrice'] = this.operateForm.courseOriginalPrice
          this.params['courseProducer'] = this.operateForm.courseProducer
          this.params['lessonNum'] = this.operateForm.lessonNum
          this.params['courseDuration'] = this.operateForm.courseDuration
          this.params['courseDiscountPrice'] = this.operateForm.courseDiscountPrice
          this.params['satisfiedScore'] = this.operateForm.satisfiedScore
          this.params['profession'] = this.operateForm.profession
          this.params['recourseSign'] = this.operateForm.recourseSign
          this.params['isOpen'] = this.operateForm.isOpen
          this.params['isHot'] = this.operateForm.isHot
          this.params['isRecommend'] = this.operateForm.isRecommend
          this.params['typeId'] = this.operateForm.typeId
          this.params['status'] = this.operateForm.status
          this.params['teacherId'] = this.operateForm.teacherId
          this.params['skillId'] = this.operateForm.skillId
          this.params['courseDetail'] = this.operateForm.courseDetail
          this.params['isSold'] = this.operateForm.isSold
          // -----------
          this.params['createName'] = 'user'
          this.params['delSign'] = 0

          this.addCourseByApi(this.params)

          // 关闭添加表单对话框
          this.closeOperateDialog()

          this.$refs.imageUpload.clearFiles()
          // 重新加载数据
          this.paramsClean()
          this.getCourse(this.params)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    updateCourse (params) {
      params.updateName = this.spId
      this.$refs['operateForm'].validate(valid => {
        if (valid) {
          this.updateCourseByApi(params).then(res => {
            this.closeOperateDialog()
            // 重新加载数据
            this.paramsClean()
            this.getCourse(this.params)
          })
        }
      })
    },
    delCourse (courseId) {
      this.delCourseByApi({ 'courseId': courseId })
    },
    addCourseBtn () {
      this.operateString = 'add'
      this.operateDisabled = false
      this.dialogTitle = '新增课程'
      this.operateForm = {
        isHot: '0',
        isOpen: '0',
        isRecommend: '0',
        isSold: '0',
        recourseSign: '0'
      }
      this.showUpdateDialog = true
    },
    updateCourseBtn (index, tableData) {
      this.operateString = 'update'
      this.operateDisabled = false
      this.dialogTitle = '修改课程'
      this.operateForm = tableData[index]
      this.showUpdateDialog = true
    },
    deleteCourseBtn (index, tableData) {
      this.delCourse(tableData[index].courseId)
      this.getCourse(this.params)
    },
    detailCourseBtn (index, tableData) {
      this.operateString = 'detail'
      this.operateDisabled = true
      this.dialogTitle = '课程详情'
      this.operateForm = tableData[index]
      this.showUpdateDialog = true
    },
    queryCourseBtn () {
      this.params['courseName'] = this.$refs['queryForm'].model.courseName
      this.params['courseProducer'] = this.$refs['queryForm'].model.courseProducer
      this.params['skillId'] = this.$refs['queryForm'].model.skillId
      this.params['status'] = this.$refs['queryForm'].model.status
      this.getCourse(this.params)
    },
    resetQueryForm (formName) {
      this.$refs[formName].resetFields()
      this.paramsClean()
      this.getCourse(this.params)
    },
    closeOperateDialog () {
      this.showUpdateDialog = false
    },
    showOperateDialog () {
      this.showUpdateDialog = true
    },
    DialogClick (params) {
      if (this.operateString === 'add') {
        this.addCourse(params)
      } else if (this.operateString === 'update') {
        this.updateCourse(this.operateForm)
      } else if (this.operateString === 'detail') {
        console.log('detail')
      }
    },
    /**
       * 【分页】点击页面，表格显示对应页面
       * @param page 点击页
       */
    handleCurrentChange (page) {
      console.log(page)
      this.page = page
      this.params.page = page
      this.getCourse(this.params)
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {
        })
    },
    paramsClean () {
      this.params = {}
      this.params.size = this.size
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handleChange (file) {
      console.log('change')
      this.operateForm.courseImagesId = uuidv1()
    },
    async getAllSkillByApi () {
      let response
      await GetAllSkill().then(res => {
        response = res
      })
      return response
    },
    async getAllTypeByApi () {
      let response
      await GetAllType().then(res => {
        response = res
      })
      return response
    },
    handleSuccess (res) {
      console.log(res)
      if (res.status === 200) {
        this.imgUrl = res.data.imgUrl
      }
    }
  },
  computed: {
    /**
     * 根据showLabel(显示的标签)和tableData(表格数据)以及colName_ch(label中文对照)处理出一个{英文label:中文label}对象
     * @return {{}} {en_label:ch_label}
     */
    colLabel () {
      let data = {}
      for (let item of this.showLabel) {
        if (this.tableData.length >= 1 && this.tableData[0].hasOwnProperty(item)) {
          data[item] = this.colName_ch[item]
        }
      }
      return data
    },
    skillNames () {
      let skillNames = {}
      if (this.skillData.length >= 1) {
        for (let item of this.skillData) {
          skillNames[item.skillId] = item.skillName
        }
      }
      return skillNames
    },
    typeNames () {
      let typeNames = {}
      if (this.typeData.length >= 1) {
        for (let item of this.typeData) {
          typeNames[item.typeId] = item.typeName
        }
      }
      return typeNames
    }
  },
  created () {
    this.paramsClean()
    this.getAllSkillByApi().then(res => {
      this.skillData = res.data
      this.getAllTypeByApi().then(res => {
        this.typeData = res.data
        this.getCourse(this.params)
      })
    })
  }
}
</script>

<style scoped>
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px 40px;
  }

  .header h1 {
    font-size: 1.6rem;
    font-weight: bold;
    margin: 0;
  }

  .header .query_form {
    display: inline-block;
    vertical-align: middle;
  }

  .header .query_form > div {
    margin: 0;
  }

  .header .query_item {
    margin-right: 20px !important;
  }

  .operate_course {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .operate_course .main {
    width: 100%!important;
  }

  .operate_course .el-form {
    width: 100%!important;
    height: 500px;
    background-color: #fff;
    position: relative;
  }

  .operate_form .main {
    box-sizing: border-box;
    overflow-y: scroll;
    width: 100%;
    height: 100%;
    padding: 20px;
  }

  .switch-div {
    display: flex;
    justify-content: left;
    flex-wrap: wrap;
  }

  .pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10px 0;
  }

  .upload {
    margin-left: 30px;
    margin-bottom: 20px;
  }

  .upload span {
    margin-left: 20px;
  }
</style>
